//
//  TheOrderViewController.m
//  BaseFrame
//
//  Created by 吕金状 on 2017/8/11.
//  Copyright © 2017年 com.mxh. All rights reserved.
//

#import "TheOrderViewController.h"
#import "TheOrderTableViewCell.h"
#import "TheOrderCollectionViewCell.h"
#import "TheOrderDetailsViewController.h"
#import "LaundryTheOrderDetailsViewController.h"
#import "MakeSureTheOrderViewController.h"
#import "MakeAnAppointmentToDoLaundryViewController.h"

@interface TheOrderViewController ()<UITableViewDelegate , UITableViewDataSource , UICollectionViewDelegate , UICollectionViewDataSource , UICollectionViewDelegateFlowLayout>
{
    NSInteger Index;//0-洗衣订单 1-购物订单
    NSString *type; //购物-查询条件(0-未付款/1-已付款(即代发货)/2-已发货/3-未评价/4-已评价) 不传为全部订单信息
}

@property (nonatomic , strong) UITableView *tableView;
@property (nonatomic , strong) UICollectionView *collectionView;
@property (nonatomic , strong) NSMutableArray *collectionDataArray;
@property (nonatomic , strong) UIView *bgView;
@property (nonatomic , strong) UIView *swipingLineView;   /**<划动的线*/
//洗衣订单数组
Strong NSMutableArray *theOrderWashArray; /**<*/

//购物订单数组
Strong NSMutableArray *theOrderArray; /**<*/
Strong NSMutableArray *theOrderSidArray; /**<*/

Strong NSMutableArray *chooseArray; /**<*/
Assign int pstart;

@end

//网络
@implementation TheOrderViewController (NetWorking)

//洗衣订单
- (void)getLaudryOrderById:(NSString *)pstart{
    [self showprogressHUD];
    NSDictionary *parameters = @{@"uId":[UserModel sharedInstanced].userId,
                                 @"lo_state":type,
                                 @"to_subdivide":@"",
                                 @"page":pstart,
                                 @"pageSize":@"10"
                                 };
    [[AFAppDotNetAPIClient sharedClient] POST:@"wardrobe/Laundry_Order/getLaudryOrderById.do" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self hiddenProgressHUD];
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        if ([responseObject[@"responseStatus"] isEqualToString:@"0"]) {
            if ([pstart isEqualToString:@"0"]) {
                [self.chooseArray removeAllObjects];
                [self.theOrderWashArray removeAllObjects];
                self.pstart = 0;
            }
            self.pstart ++;
            [self.theOrderWashArray addObjectsFromArray:responseObject[@"data"]];
            [self.tableView reloadData];
        }else{
            ShowMessage(responseObject[@"msg"]);
            [self.theOrderWashArray removeAllObjects];
            [self.tableView reloadData];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        [self showError:error];
        [self hiddenProgressHUD];
    }];
}

/**
 购物订单
 */
- (void)viewUserOrders:(NSString *)pstart{
    [self showprogressHUD];
    NSDictionary *parameters = @{@"auId":[UserModel sharedInstanced].userId,
                                 @"psize":@"10",
                                 @"pstart":pstart,
                                 @"soState":type};
    [[AFAppDotNetAPIClient sharedClient] POST:@"LaundryMall/Store_Order/viewUserOrders.action" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self hiddenProgressHUD];
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        if ([responseObject[@"responseStatus"] isEqualToString:@"0"]) {
            if ([pstart isEqualToString:@"0"]) {
                [self.chooseArray removeAllObjects];
                [self.theOrderArray removeAllObjects];
                [self.theOrderSidArray removeAllObjects];
                self.pstart = 0;
            }
            self.pstart ++;
            [self.theOrderSidArray addObjectsFromArray:responseObject[@"obj"]];
            [self.theOrderArray addObjectsFromArray:responseObject[@"obj1"]];
            [self.tableView reloadData];
        }else{
            ShowMessage(responseObject[@"msg"]);
            [self.theOrderArray removeAllObjects];
            [self.theOrderSidArray removeAllObjects];
            [self.tableView reloadData];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        [self showError:error];
        [self hiddenProgressHUD];
    }];
}

//批量删除洗衣订单
- (void)deleteLaundryOrder{
    [self showprogressHUD];
    NSMutableArray *loIdArray = [NSMutableArray array];
    for (int i = 0; i < self.chooseArray.count; i++) {
        int j = [self.chooseArray[i] intValue];
        [loIdArray addObject:self.theOrderWashArray[j][@"lo_id"]];
    }
    
    NSDictionary *parameters = @{@"loId":[loIdArray componentsJoinedByString:@","]};
    [[AFAppDotNetAPIClient sharedClient] POST:@"wardrobe/Laundry_Order/deleteLaundryOrder.do" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self hiddenProgressHUD];
        if ([responseObject[@"responseStatus"] isEqualToString:@"0"]) {
            ShowMessage(responseObject[@"msg"]);
            [self getLaudryOrderById:@"0"];
        }else{
            ShowMessage(responseObject[@"msg"]);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self showError:error];
        [self hiddenProgressHUD];
    }];
}

/**
 批量删除购物订单
 */
- (void)bulkDeleteOrder{
    [self showprogressHUD];
    NSMutableArray *soIdArray = [NSMutableArray array];
    for (int i = 0; i < self.chooseArray.count; i++) {
        int j = [self.chooseArray[i] intValue];
        [soIdArray addObject:self.theOrderArray[j][0][@"so_id"]];
    }
    
    NSDictionary *parameters = @{@"soId":[soIdArray componentsJoinedByString:@","]};
    [[AFAppDotNetAPIClient sharedClient] POST:@"LaundryMall/Store_Order/bulkDeleteOrder.action" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self hiddenProgressHUD];
        if ([responseObject[@"responseStatus"] isEqualToString:@"0"]) {
            ShowMessage(responseObject[@"msg"]);
            [self viewUserOrders:@"0"];
        }else{
            ShowMessage(responseObject[@"msg"]);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self hiddenProgressHUD];
        [self showError:error];
    }];
}

//预约洗衣
-  (void)viewCommodityInformation{
    [self showprogressHUD];
    NSDictionary *parameters = @{@"longitude":[UserModel sharedInstanced].longitude,
                                 @"latitude":[UserModel sharedInstanced].latitude};
    [[AFAppDotNetAPIClient sharedClient] POST:@"wardrobe/Mobile_Phone_Terminal/viewCommodityInformation.do" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self hiddenProgressHUD];
        if ([responseObject[@"responseStatus"] isEqualToString:@"0"]) {
            MakeAnAppointmentToDoLaundryViewController *vc = [MakeAnAppointmentToDoLaundryViewController new];
            vc.hidesBottomBarWhenPushed = YES;
            vc.aId = responseObject[@"obj"][0][@"a_id"];
            [self.navigationController pushViewController:vc animated:YES];
        }else{
            ShowMessage(responseObject[@"msg"]);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self hiddenProgressHUD];
        [self showError:error];
    }];
}


@end


//UI
@implementation TheOrderViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSArray *segmentedArray = [[NSArray alloc]initWithObjects:@"洗衣订单",@"购物订单",nil];
    //初始化UISegmentedControl
    self.navigationItem.titleView = ({
        UISegmentedControl *segmentedControl = [[UISegmentedControl alloc]initWithItems:segmentedArray];
        segmentedControl.frame = CGRectMake(0, 0 , 200 , 30);
        // 设置默认选择项索引
        segmentedControl.selectedSegmentIndex = 0;
        [segmentedControl addTarget:self action:@selector(didClicksegmentedControlAction:) forControlEvents:UIControlEventValueChanged];
        segmentedControl.layer.cornerRadius = 15;
        segmentedControl;
    });
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"delete"] style:UIBarButtonItemStylePlain target:self action:@selector(rightBarButtonItemClick)];
    [self.view addSubview:self.collectionView];
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.bgView];
    [self.view addSubview:self.swipingLineView];
    
    type = @"";
    [self getLaudryOrderById:@"0"];
}


- (void)viewWillAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(nTestViewDidClickBtn) name:@"预约洗衣" object:nil];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)nTestViewDidClickBtn{
    [self viewCommodityInformation];
}

#pragma mark - init

- (UIView *)swipingLineView{
    if (!_swipingLineView) {
        _swipingLineView = [[UIView alloc]initWithFrame:CGRectMake(-0.25, 31 / WIDTH_5S_SCALE, SCREEN_WIDTH / self.collectionDataArray.count, 3)];
        _swipingLineView.backgroundColor = getColor(mainColor);
    }
    return _swipingLineView;
}

- (UIView *)bgView{
    if (!_bgView) {
        _bgView = [[UIView alloc]initWithFrame:CGRectMake(0, self.collectionView.bounds.size.height + self.swipingLineView.height, SCREEN_WIDTH, 5 / WIDTH_5S_SCALE)];
        _bgView.backgroundColor = getColor(@"eeeeee");
    }
    return _bgView;
}

- (UICollectionView *)collectionView{
    if (!_collectionView) {
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
        [flowLayout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
        flowLayout.minimumInteritemSpacing = 0;
        flowLayout.minimumLineSpacing = 0;
        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH , 31 / WIDTH_5S_SCALE) collectionViewLayout:flowLayout];
        [_collectionView registerClass:[TheOrderCollectionViewCell class] forCellWithReuseIdentifier:@"UICollectionView"];
        _collectionView.backgroundColor = getColor(@"ffffff");
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
    }
    return _collectionView;
}

- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, self.collectionView.bounds.size.height + self.swipingLineView.bounds.size.height + self.bgView.bounds.size.height, SCREEN_WIDTH,SCREEN_HEIGHT - self.collectionView.bounds.size.height - 64 - self.swipingLineView.bounds.size.height - self.bgView.bounds.size.height - 49)];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.separatorInset = UIEdgeInsetsZero;
        if([_tableView respondsToSelector:@selector(setLayoutMargins:)]){
            _tableView.layoutMargins=UIEdgeInsetsZero;
        }
        _tableView.backgroundColor = getColor(@"ffffff");
        _tableView.tableFooterView = [[UIView alloc]init];
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            if (Index == 0) {
                [self getLaudryOrderById:@"0"];
            }else{
                [self viewUserOrders:@"0"];
            }
        }];
        _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            if (Index == 0) {
                [self getLaudryOrderById:[NSString stringWithFormat:@"%d",self.pstart]];
            }else{
                [self viewUserOrders:[NSString stringWithFormat:@"%d",self.pstart]];
            }
        }];
    }
    return _tableView;
}

#pragma mark - click

- (void)rightBarButtonItemClick{
    NSLog(@"删除");
    //有效判断
    if (self.chooseArray.count <= 0) {
        ShowMessage(@"请先选择要删除的数据");
        return;
    }
    
    if (Index == 0) {
        //批量删除洗衣订单
        [self deleteLaundryOrder];
    }else{
        //批量删除购物订单
        [self bulkDeleteOrder];
    }
}

#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (Index == 0) {
        return self.theOrderWashArray.count;
    }
    return self.theOrderArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    TheOrderTableViewCell * cell = [TheOrderTableViewCell cellForTableView:tableView];
    cell.indexPath = indexPath;
    cell.chooseArray = self.chooseArray;
    
    if (Index == 1) {
        //购物订单
        cell.modelSid = self.theOrderSidArray[indexPath.row];
        cell.model = self.theOrderArray[indexPath.row][0];
    }else{
        //洗衣订单
        cell.modelWash = self.theOrderWashArray[indexPath.row];
    }
    
    cell.getChooseClick = ^{
        if (![self.chooseArray containsObject:[NSString stringWithFormat:@"%d",(int)indexPath.row]]) {
            [self.chooseArray addObject:[NSString stringWithFormat:@"%d",(int)indexPath.row]];
        }else{
            [self.chooseArray removeObject:[NSString stringWithFormat:@"%d",(int)indexPath.row]];
        }
        [self.tableView reloadData];
    };
    return cell;
    
}

#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 80 / WIDTH_5S_SCALE;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (Index == 0) {
        LaundryTheOrderDetailsViewController *vc = [LaundryTheOrderDetailsViewController new];
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
    }else{
        if ([self.theOrderSidArray[indexPath.row][@"so_state"] isEqualToString:@"0"]) {
//            未付款
            MakeSureTheOrderViewController *vc = [MakeSureTheOrderViewController new];
            vc.hidesBottomBarWhenPushed = YES;
            vc.so_id = self.theOrderSidArray[indexPath.row][@"so_id"];
            [self.navigationController pushViewController:vc animated:YES];
        }else if([self.theOrderSidArray[indexPath.row][@"so_state"] isEqualToString:@"1"]){
            TheOrderDetailsViewController *vc = [TheOrderDetailsViewController new];
            vc.hidesBottomBarWhenPushed = YES;
            vc.so_id = self.theOrderSidArray[indexPath.row][@"so_id"];
            [self.navigationController pushViewController:vc animated:YES];
        }else if([self.theOrderSidArray[indexPath.row][@"so_state"] isEqualToString:@"2"]){
            TheOrderDetailsViewController *vc = [TheOrderDetailsViewController new];
            vc.hidesBottomBarWhenPushed = YES;
            vc.so_id = self.theOrderSidArray[indexPath.row][@"so_id"];
            [self.navigationController pushViewController:vc animated:YES];
        }else if([self.theOrderSidArray[indexPath.row][@"so_state"] isEqualToString:@"3"]){
            TheOrderDetailsViewController *vc = [TheOrderDetailsViewController new];
            vc.hidesBottomBarWhenPushed = YES;
            vc.so_id = self.theOrderSidArray[indexPath.row][@"so_id"];
            [self.navigationController pushViewController:vc animated:YES];
        }else if([self.theOrderSidArray[indexPath.row][@"so_state"] isEqualToString:@"4"]){
            TheOrderDetailsViewController *vc = [TheOrderDetailsViewController new];
            vc.hidesBottomBarWhenPushed = YES;
            vc.buttonType = YES;
            vc.so_id = self.theOrderSidArray[indexPath.row][@"so_id"];
            [self.navigationController pushViewController:vc animated:YES];
        }
    }
}

#pragma mark - UICollectionViewDataSource

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.collectionDataArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    TheOrderCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"UICollectionView" forIndexPath:indexPath];
    cell.model = self.collectionDataArray[indexPath.row];
    return cell;
}


#pragma mark -  UICollectionViewDelegate

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    [UIView animateWithDuration:.5 animations:^{
        self.swipingLineView.frame = CGRectMake(indexPath.row * (SCREEN_WIDTH / self.collectionDataArray.count), self.collectionView.height, SCREEN_WIDTH / self.collectionDataArray.count, 3);
    }];
    
    //订单状态
    if (indexPath.row == 0) {
        type = @"";
    }else{
        type = [NSString stringWithFormat:@"%ld",indexPath.row - 1];
    }
    
    if (Index == 0) {
        //洗衣订单
        [self getLaudryOrderById:@"0"];
    }else{
        //购物订单
        [self viewUserOrders:@"0"];
    }
    
    [self.collectionDataArray[indexPath.row] setObject:mainColor forKey:@"textColor"];
    for (int i = 0 ; i < self.collectionDataArray.count ; i ++) {
        if (i != indexPath.row) {
            [self.collectionDataArray[i] setObject:textColor forKey:@"textColor"];
        }
    }
    [self.collectionView reloadData];
}

#pragma mark - UICollectionViewDelegateFlowLayout

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake(SCREEN_WIDTH / self.collectionDataArray.count, 31 / WIDTH_5S_SCALE);
}

#pragma mark - click

-(void)didClicksegmentedControlAction:(UISegmentedControl *)Seg{
    type = @"";
    Index = Seg.selectedSegmentIndex;
    if (Index != 0) {
        self.collectionDataArray = @[@{@"title":@"全部",@"textColor":mainColor}.mutableCopy,
                                     @{@"title":@"待支付",@"textColor":textColor}.mutableCopy,
                                     @{@"title":@"待发货",@"textColor":textColor}.mutableCopy,
                                     @{@"title":@"待收货",@"textColor":textColor}.mutableCopy,
                                     @{@"title":@"待评价",@"textColor":textColor}.mutableCopy,
                                     ].mutableCopy;
        [self viewUserOrders:@"0"];
    }else{
        self.collectionDataArray = @[@{@"title":@"全部",@"textColor":mainColor}.mutableCopy,
                                     @{@"title":@"待支付",@"textColor":textColor}.mutableCopy,
                                     @{@"title":@"待发货",@"textColor":textColor}.mutableCopy,
                                     @{@"title":@"已到柜",@"textColor":textColor}.mutableCopy,
                                     @{@"title":@"已收货",@"textColor":textColor}.mutableCopy,
                                     ].mutableCopy;
        [self getLaudryOrderById:@"0"];
    }
    [UIView animateWithDuration:.5 animations:^{
        self.swipingLineView.frame = CGRectMake(-0.25, 31 / WIDTH_5S_SCALE, SCREEN_WIDTH / self.collectionDataArray.count, 3);
    }];
    [self.collectionDataArray[0] setObject:mainColor forKey:@"textColor"];
    for (int i = 0 ; i < self.collectionDataArray.count ; i ++) {
        if (i != 0) {
            [self.collectionDataArray[i] setObject:textColor forKey:@"textColor"];
        }
    }
    [self.collectionView reloadData];
}

#pragma  mark - data

/**
 购物订单数组
 
 @return return value description
 */
- (NSMutableArray *)theOrderArray{
    if (!_theOrderArray) {
        _theOrderArray  = @[
                            ].mutableCopy;
    }
    return _theOrderArray;
}

- (NSMutableArray *)theOrderSidArray{
    if (!_theOrderSidArray) {
        _theOrderSidArray = @[].mutableCopy;
    }
    return _theOrderSidArray;
}

- (NSMutableArray *)theOrderWashArray{
    if (!_theOrderWashArray) {
        _theOrderWashArray = @[].mutableCopy;
    }
    return _theOrderWashArray;
}

- (NSMutableArray *)collectionDataArray{
    if (!_collectionDataArray) {
        _collectionDataArray = @[@{@"title":@"全部",@"textColor":mainColor}.mutableCopy,
                                 @{@"title":@"待支付",@"textColor":textColor}.mutableCopy,
                                 @{@"title":@"待发货",@"textColor":textColor}.mutableCopy,
                                 @{@"title":@"已到柜",@"textColor":textColor}.mutableCopy,
                                 @{@"title":@"已收货",@"textColor":textColor}.mutableCopy,
                                 ].mutableCopy;
    }
    return _collectionDataArray;
}

- (NSMutableArray *)chooseArray{
    if (!_chooseArray) {
        _chooseArray = @[].mutableCopy;
    }
    return _chooseArray;
}

@end
